<template>
  <div class="mobile_index_wrap">
    <!-- 用户信息 -->
    <div class="user_box">
      <!-- <el-card style="background-color: transparent"> -->
      <div class="user_card_box">
        <div class="left_box">
          <img class="avatar_img" src="./image/avatar.svg" alt="" srcset="" />
          <div class="text_box">
            <span class="user_name">{{ userStore.userInfo.name }}，</span>
            <span class="welcome_text">{{ getTimeOfDay() }}好！</span>
          </div>
        </div>
        <div class="right_box">
          <div class="action_box">
            <van-button type="primary" size="small" @click="editPassClick">
              <img class="ac_icon edit_pass" src="./image/edit_pass_icon.svg" />
              修改密码
            </van-button>
            <van-button type="danger" style="margin-top: 10px" size="small" @click="loginOutClick">
              <img class="ac_icon logout" src="./image/logout_icon.svg" />
              退出登录
            </van-button>
          </div>
        </div>
      </div>
      <!-- </el-card> -->
    </div>

    <!--功能栏 -->
    <div class="fun_column_box">
      <div class="fun_item_box" v-for="(func, indexF) in funListComp" :key="indexF" @click="funItemClick(func)">
        <div class="left_box">
          <img class="fun_icon_img" v-if="func.icon == 'leibie'" src="./image/leibie.svg" />
          <img class="fun_icon_img" v-if="func.icon == 'shiyanshi'" src="./image/shiyanshi.svg" />
          <img class="fun_icon_img" v-if="func.icon == 'shiyanyuan'" src="./image/shiyanyuan.svg" />
          <img class="fun_icon_img" v-if="func.icon == 'duliang'" src="./image/duliang.svg" />
          <img class="fun_icon_img" v-if="func.icon == 'huopin'" src="./image/huopin.svg" />
          <span class="fun_name_box">
            {{ func.funName }}
          </span>
        </div>
        <div class="right_box">
          <img class="go_icon_img" src="./image/go.svg" />
        </div>
      </div>
    </div>

    <!-- 修改密码弹窗 -->
    <van-dialog
      v-model:show="isShowEditPassDialog"
      title="修改密码"
      show-cancel-button
      show-confirm-button
      :close-on-click-overlay="true"
      @confirm="editPassConfirmClick"
      :before-close="editPassDialogBeforeClose"
    >
      <div class="edit_form_box">
        <van-form @failed="onFailed" ref="editPassFormRef">
          <van-cell-group inset>
            <van-field
              v-model="editPassFormData.oldPass"
              name="validator"
              label="旧密码"
              placeholder="请输入旧密码"
              type="password"
              :rules="[{ validator: oldPassV, message: '旧密码不能为空' }]"
            />
            <!-- 通过 validator 返回错误提示 -->
            <van-field
              v-model="editPassFormData.newPass"
              label="新密码"
              name="validatorMessage"
              placeholder="请输入新密码"
              type="password"
              :rules="[{ validator: newPassV, message: '新密码不能为空' }]"
            />
            <!-- 通过 validator 进行异步函数校验 -->
            <van-field
              label="确认密码"
              v-model="editPassFormData.confirmPass"
              name="asyncValidator"
              placeholder="请输入再次输入新密码"
              type="password"
              :rules="[{ validator: confirmPassV, message: '请输入再次输入新密码' }]"
            />
          </van-cell-group>
          <!-- <div style="margin: 16px">
            <van-button round block type="primary" native-type="submit"> 提交 </van-button>
          </div> -->
        </van-form>
      </div>
    </van-dialog>
  </div>
</template>

<script lang="ts">
import { computed, defineComponent, ref, watch } from "vue";
import "./index.scss";
import { showToast } from "vant";
export default defineComponent({
  name: "MobileIndex"
});
</script>
<script lang="ts" setup>
import { useUserStore } from "@/stores/modules/user";
import { useAuthStore } from "@/stores/modules/auth";
import { useRouter } from "vue-router";
import { LOGIN_URL } from "@/config";
import dayjs from "dayjs";
import { showConfirmDialog, showNotify } from "vant";
import { editPswApi } from "@/api/modules/experimentalist";

const userStore = useUserStore();
const authStore = useAuthStore();
const router = useRouter();

// 功能列表计算属性
const funListComp = computed(() => {
  let funL = [];
  let isM = userStore.userInfo.isManager;
  if (isM == 1) {
    funL = [
      {
        funName: "货品管理",
        path: "/goodsMobile/index",
        icon: "huopin",
        bgc: ""
      }
      // {
      //   funName: "实验室管理",
      //   path: "/laboratoryMobile/index",
      //   icon: "shiyanshi",
      //   bgc: ""
      // },
      // {
      //   funName: "实验员管理",
      //   path: "/experimentalist/index",
      //   icon: "shiyanyuan",
      //   bgc: ""
      // }
      // {
      //   funName: "类别管理",
      //   path: "/category/index",
      //   icon: "leibie",
      //   bgc: ""
      // }
      // {
      //   funName: "度量管理",
      //   path: "/measurement/index",
      //   icon: "duliang",
      //   bgc: ""
      // }
    ];
  } else if (isM == 0) {
    funL = [
      {
        funName: "货品管理",
        path: "/goods/index",
        icon: "huopin",
        bgc: ""
      }
    ];
  }
  return funL;
});

// 功能项点击事件
const funItemClick = func => {
  router.push({
    path: func.path
  });
};

// 功能栏列表
// const funColumnList = ref([
//   {
//     funName: "货品管理",
//     path: "/goods/index",
//     icon: "huopin",
//     bgc: ""
//   },
//   {
//     funName: "实验室管理",
//     path: "/laboratory/index",
//     icon: "shiyanshi",
//     bgc: ""
//   },
//   {
//     funName: "实验员管理",
//     path: "/experimentalist/index",
//     icon: "shiyanyuan",
//     bgc: ""
//   },
//   {
//     funName: "类别管理",
//     path: "/category/index",
//     icon: "leibie",
//     bgc: ""
//   },
//   {
//     funName: "度量管理",
//     path: "/measurement/index",
//     icon: "duliang",
//     bgc: ""
//   }
// ]);

// 修改密码弹窗关闭前回调
const editPassDialogBeforeClose = e => {
  if (e == "confirm") {
    return editPassConfirmVFunc();
  } else {
    return true;
  }
};

// 修改密码表单Ref
const editPassFormRef = ref(null);

// 修改密码表单数据
const editPassFormData = ref({
  oldPass: "",
  newPass: "",
  confirmPass: ""
});
// const pattern = /\d{6}/;

// 校验函数返回 true 表示校验通过，false 表示不通过
// const validator = val => /1\d{10}/.test(val);

// 校验函数可以直接返回一段错误提示
// const validatorMessage = val => `${val} 不合法，请重新输入`;

// 旧密码校验
const oldPassV = val => {
  console.log(val);
  return new Promise((resolve, reject) => {
    if (editPassFormData.value.oldPass == "") {
      resolve(val === "reject");
    } else {
      reject();
    }
  });
};

// 新密码校验
const newPassV = val => {
  console.log(val);
  return new Promise((resolve, reject) => {
    if (editPassFormData.value.newPass == "") {
      resolve(val === "reject");
    } else {
      reject();
    }
  });
};

// 确认密码校验
const confirmPassV = val => {
  console.log(val);
  return new Promise((resolve, reject) => {
    if (editPassFormData.value.confirmPass == "") {
      resolve(val === "reject");
    } else {
      reject();
    }
  });
};

const onFailed = errorInfo => {
  console.log("failed", errorInfo);
};

// 显示修改密码弹窗的标识
const isShowEditPassDialog = ref(false);

// 监听修改密码弹窗标识
watch(isShowEditPassDialog, (newStatus, oldStatus) => {
  console.log("变化了", newStatus);
  if (!newStatus) {
    editPassFormRef.value.resetValidation();
  }
});

// 修改密码确定验证函数
const editPassConfirmVFunc = () => {
  let flag;
  if (editPassFormData.value.oldPass != "" && editPassFormData.value.newPass != "" && editPassFormData.value.oldPass != "") {
    if (editPassFormData.value.confirmPass != editPassFormData.value.newPass) {
      flag = false;
      showToast("两次输入密码不一致");
      return flag;
    } else {
      flag = true;
      return flag;
    }
  } else if (editPassFormData.value.oldPass == "") {
    flag = false;
    showToast("旧密码不能为空");
    return flag;
  } else if (editPassFormData.value.newPass == "") {
    flag = false;
    showToast("新密码不能为空");
    return flag;
  } else if (editPassFormData.value.confirmPass == "") {
    flag = false;
    showToast("确认密码不能为空");
    return flag;
  }
  return flag;
};

// 修改密码确定点击事件
const editPassConfirmClick = async () => {
  // 判断验证
  if (editPassConfirmVFunc()) {
    isShowEditPassDialog.value = false;
    await editPswApi({
      tbLabUserId: userStore.userInfo.id,
      oldPsw: editPassFormData.value.oldPass,
      newPsw: editPassFormData.value.newPass
    })
      .then(res => {
        console.log("修改成功", res);
        if (res.result == "success") {
          showToast("修改成功");
          loginOutDisposeFunc();
        } else if (res.result == "error") {
          showToast(res.msg);
        }
      })
      .catch(err => {
        showToast("修改失败");
      });
  } else {
  }
};

// 修改密码点击事件
const editPassClick = () => {
  isShowEditPassDialog.value = true;
};

// 退出登录执行函数
const loginOutDisposeFunc = () => {
  userStore.setToken("");
  localStorage.clear();
  sessionStorage.clear();
  authStore.authMenuList = [];

  // 3.重定向到登陆页
  router.replace(LOGIN_URL);
  // ElMessage.success("退出登录成功！");
  // showToast("退出登录成功!");
  showNotify({ type: "success", message: "退出登录成功!" });
};
// 退出登录点击事件
const loginOutClick = () => {
  // 提示框
  showConfirmDialog({
    title: "提示",
    message: "确定退出登录吗?"
  })
    .then(() => {
      loginOutDisposeFunc();
    })
    .catch(() => {
      // on cancel
    });
};

// 时间段推算函数
function getTimeOfDay() {
  const now = dayjs();
  const hour = now.hour();

  if (hour >= 6 && hour < 10) {
    return "早上";
  } else if (hour >= 10 && hour < 13) {
    return "中午";
  } else if (hour >= 13 && hour < 18) {
    return "下午";
  } else if (hour >= 18 && hour < 24) {
    return "晚上";
  } else {
    return "凌晨";
  }
}
</script>

<style lang="scss" scoped></style>
